﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using DrillingTrack3D.Model;
using Nancy;
using Nancy.ModelBinding;
using Nancy.Routing;
using Nancy.Security;

namespace DrillSite.Controller
{
    public partial class DrillController : NancyModule
    {
        private const string shendu = "深度";
        private const string jiaodu = "角度";

        public DrillController(IRouteCacheProvider routeCacheProvider)
        {
            Before += ctx => {
                return ctx.Response;
            };
            Get["/sayhello"] = _ =>
            {
                return "Hello from Nancy";
            };

            Post["/bind"] = p =>
            {
                var f = this.Bind<List<LoginModel>>();
                return Response.AsJson(f);
            };

            Get["/{category}"] = _ =>
            {
               
                return "My category is " + _.category;
            };

          

            Get["/"] = p =>
            {
                return View["index"];
            };

            Get["/trajectory"] = p =>
            {
                return View["trajectory"];
            };
            Get["/trajectory-nonav"] = p =>
            {
                return View["trajectory-nonav"];
            };

            Get["/depth"] = p =>
            {
                return View["depth"];
            }; 
            
            Get["/depth-nonav"] = p =>
            {
                return View["depth-nonav"];
            };

            Get["/angle"] = p =>
            {
                return View["angle"];
            }; 

            Get["/editor"] = p =>
            {
                return View["editor"];
            };

            Get[@"/GetHoleShenduIds"] = GetHoleShenduIds;
            Get[@"/GetHoleJiaoduIds"] = GetHoleJiaoduIds;

            Get["/GetHoleShenduData"] = GetHoleShenduData;

            Get["/GetHoleJiaoduData"] = GetHoleJiaoduData;
        }

        

        private object GetHoleShenduIds(object arg)
        {
            int pageSize = int.Parse(Request.Query["pageSize"]);
            int pageNum = int.Parse(Request.Query["pageNum"]);

            var path = Path.Combine(Response.RootPath, "Data", shendu);
            return GetHoleIds(pageSize, pageNum, path);
        }

        private object GetHoleJiaoduIds(object arg)
        {
            int pageSize = int.Parse(Request.Query["pageSize"]);
            int pageNum = int.Parse(Request.Query["pageNum"]);

            var path = Path.Combine(Response.RootPath, "Data", jiaodu);
            return GetHoleIds(pageSize, pageNum, path);
        }

        private object GetHoleIds(int pageSize,int pageNum,string path)
        {
            var files = Directory.GetFiles(path);

            var group = files.Select(o => new {createTime = File.GetCreationTime(o).ToString("yyyy-MM-dd"), fileName = Path.GetFileNameWithoutExtension(o)})
                .GroupBy(o => o.createTime)
                .OrderByDescending(o => o.Key);

            var page = group
                .Skip(pageSize*(pageNum - 1))
                .Take(pageSize);

            var pagedResult = new Select2PagedResult
            {
                Total = group.Count(),
                Results = page.Select(o => new Select2Group
                {
                    Group = o.Key,
                    Options = o.Select(t => new Select2Result
                    {
                        id = t.fileName,
                        text = t.fileName
                    }).ToList()
                }).ToList(),
            };

            return Response.AsJson(pagedResult);
        }

        private object GetHoleShenduData(object arg)
        {
            var holeIds = Request.Query["holeId[]"].Value;


            return GetHoleData(holeIds, shendu);
        }

        private object GetHoleJiaoduData(object arg)
        {
            var holeIds = Request.Query["holeId[]"].Value;


            return GetHoleData(holeIds, jiaodu);
        }

        private object GetHoleData(string holeIds, string path)
        {
            if (holeIds == null) return null;
            string[] listHoleId = holeIds.Split(',');

            var result = new Dictionary<string, List<XYZModel>>();
            if (listHoleId.Any())
            {
                foreach (var holeId in listHoleId)
                {
                    var list = new List<XYZModel>();
                    string fileName = string.Format("{0}Data\\{2}\\{1}.txt", AppDomain.CurrentDomain.BaseDirectory, holeId, path);

                    using (var sr = new StreamReader(fileName, Encoding.Default))
                    {
                        string s;
                        while ((s = sr.ReadLine()) != null)
                        {
                            string[] model = s.Split('^');

                            if (path == "深度")
                            {
                                list.Add(new XYZModel(model[0].Trim(), model[1].Trim(), model[2].Trim(), model[3].Trim(), model[4].Trim(), model[5].Trim(), model[6].Trim()));
                            }
                            else
                            {
                                list.Add(new XYZModel(model[0].Trim(), model[1].Trim(), model[2].Trim(), model[3].Trim(), model[4].Trim(), model[5].Trim()
                                    , model[6].Trim(), model[7].Trim(), model[8].Trim()));
                            }
                        }
                        sr.Close();
                    }
                    result.Add(holeId, list);
                }
            }

            return Response.AsJson(result);
        }
    }

    public class LoginModel
    {
        public bool RememberMe { get; set; }

        public List<int> Ints { get; set; } 
    }

    public class Select2PagedResult
    {
        public int Total { get; set; }

        public List<Select2Group> Results { get; set; }
    }

    public class Select2Group
    {
        public string Group { get; set; }

        public List<Select2Result> Options { get; set; }
    }

    public class Select2Result
    {
        public string id { get; set; }
        public string text { get; set; }
    }
}
